import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONObject;

import com.caucho.hessian.client.HessianProxyFactory;
import com.max.mil.model.GraContent;
import com.max.mil.share.GraContentService;
import com.tencent.weibo.oauthv1.OAuthV1;


public class MaxTools
{
	
	static String[] tokenInfoArr = new String[]{
		"af51069722f04c15911cdf25b91bfe58|81a98d6117ad686eb3aad86061707e4a",
		"af51069722f04c15911cdf25b91bfe58|81a98d6117ad686eb3aad86061707e4a",
		"af51069722f04c15911cdf25b91bfe58|81a98d6117ad686eb3aad86061707e4a"};
	
	
	public static void uploadPic(String basePath) throws Exception
	{
		/**1.初始化OAuth*/
		OAuthV1 oAuth = new OAuthV1();
		oAuth.setOauthConsumerKey("801115505");
		oAuth.setOauthConsumerSecret("be1dd1410434a9f7d5a2586bab7a6829");
		TAPIExtend tpai = new TAPIExtend(oAuth.getOauthVersion());
		
		
		/**2.遍历待上传目录*/
		File dir = new File(basePath);
		File[] subDirs = dir.listFiles(new FileFilter()
			{
				@Override
				public boolean accept(File f)
				{
					if(f.isDirectory() && !f.getName().contains("svn")
							&& !f.getName().matches("\\d{8}-\\d{3}.*"))
						return true;
					else
						return false;
				}
			});
		
		/**3.遍历待上传目录下的文件*/
		int count = 0;
		int picTotal = 0;
		for(File subDir:subDirs)
		{
			System.out.println("pre upload:" + subDir.getPath());
			StringBuffer readme = new StringBuffer();
			File readmeTxt = new File(subDir.getPath() + "/README.TXT");
			
			File[] validFiles = subDir.listFiles(new FileFilter()
			{
				List<String> picSuffixList = Arrays.asList(new String[]{"jpg","jpeg"});
				
				@Override
				public boolean accept(File f)
				{
					String tmpName = f.getName();
					if(f.isFile() && tmpName.indexOf(".") > 0 
							&& picSuffixList.contains(tmpName.substring(tmpName.lastIndexOf(".")+1)))
						return true;
					else
						return false;
				}});
			
			for(File validFile:validFiles)
			{
				System.out.println("pre upload:" + validFile.getPath());
				
				String tokenInfo = tokenInfoArr[picTotal++%tokenInfoArr.length];
				oAuth.setOauthToken(tokenInfo.split("\\|")[0]);
				oAuth.setOauthTokenSecret(tokenInfo.split("\\|")[1]);
				
				String resp = tpai.uploadPic(oAuth, "json", null, validFile.getPath(), 2);
				JSONObject json = JSONObject.fromObject(resp);
				if(json.getInt("ret") == 0 && json.getJSONObject("data") != null
						&& json.getJSONObject("data").get("imgurl") != null)
				{
					System.out.println(json.getJSONObject("data").get("imgurl"));
					readme.append(validFile.getName()).append("\t")
						  .append(json.getJSONObject("data").get("imgurl"))
						  .append(System.getProperty("line.separator"));
				}
				else
					throw new Exception();
				
				Thread.sleep(3000);
			}
			
			
			if(readme.length()>0)
			{
				//写README.TXT文件
				FileOutputStream out = new FileOutputStream(readmeTxt);
				out.write(readme.toString().getBytes());
				out.close();
				
				//文件夹重命名
				count++;
				StringBuffer newSubDir = new StringBuffer();
				newSubDir.append(subDir.getParent()).append("/")
						 .append(new SimpleDateFormat("yyyyMMdd").format(new Date())).append("-");
				for (int i = 3; i > String.valueOf(count).length(); i--)
					newSubDir.append("0");
				newSubDir.append(count);
				newSubDir.append("_").append(subDir.getName());
				subDir.renameTo(new File(newSubDir.toString()));
			}
		}
	}
	
	
	public static void addWeibo(String basePath) throws Exception
	{
		/**1.初始化OAuth*/
		OAuthV1 oAuth = new OAuthV1();
		oAuth.setOauthConsumerKey("801115505");
		oAuth.setOauthConsumerSecret("be1dd1410434a9f7d5a2586bab7a6829");
		oAuth.setOauthToken("af51069722f04c15911cdf25b91bfe58");
		oAuth.setOauthTokenSecret("81a98d6117ad686eb3aad86061707e4a");
		TAPIExtend tpai = new TAPIExtend(oAuth.getOauthVersion());
		
		
		/**2.遍历待上传目录*/
		File dir = new File(basePath);
		File[] subDirs = dir.listFiles(new FileFilter()
			{
				@Override
				public boolean accept(File f)
				{
					if(f.isDirectory() && !f.getName().contains("svn")
							&& f.getName().matches("\\d{8}-\\d{3}.*"))
						return true;
					else
						return false;
				}
			});
		
		/**3.遍历待上传目录下的文件*/
		for(File subDir:subDirs)
		{
			File[] validFiles = subDir.listFiles(new FileFilter()
			{
				@Override
				public boolean accept(File f)
				{
					if(f.isFile() && f.getName().equals("README.TXT"))
						return true;
					else
						return false;
				}});
			
			for(File validFile:validFiles)
			{
				System.out.println("pre upload:" + validFile.getPath());
				
				List<String> list = file2List(validFile);
				String pic_url = null;
				for(int i=0; i<list.size(); i++)
				{
					pic_url += (list.get(i).split("\\t")[1]+",");
					if(i%8==0 || i==list.size()-1)
					{
						String resp = tpai.addPic(oAuth, "json", subDir.getName(), "127.0.0.1", "", "", pic_url, "1");
						JSONObject json = JSONObject.fromObject(resp);
						if(json.getInt("ret") != 0)
							throw new Exception();

						pic_url = null;
					}
				}
			}
			
			subDir.renameTo(new File(subDir.getParent()+"/"+subDir.getName()+"_T"));
		}
	}
	
	
	public static void uploadMil(String basePath) throws Exception
	{
		/**1.初始化Hessian*/
		String url = "http://127.0.0.1:8080/hessian/graContentService";
		HessianProxyFactory factory = new HessianProxyFactory();
		GraContentService graContentService = (GraContentService)factory.create(GraContentService.class, url);
		
		
		/**2.遍历待上传目录*/
		File dir = new File(basePath);
		StringBuffer readme = new StringBuffer();
		File readmeTxt = new File(dir.getPath() + "/README.TXT");
		if(!readmeTxt.exists())readmeTxt.createNewFile();
		
		List<String> conList = file2List(readmeTxt);
		Set<String> conSet = null;
		if(conList != null && !conList.isEmpty())
		{
			conSet = new HashSet<String>();
			for(String con:conList)
				conSet.add(con.split("\\t")[0]);
		}
		
		
		File[] subDirs = dir.listFiles(new FileFilter()
			{
				@Override
				public boolean accept(File f)
				{
					if(f.isDirectory() && !f.getName().contains("svn")
							&& f.getName().matches("\\d{8}-\\d{3}.*"))
						return true;
					else
						return false;
				}
			});
		
		/**3.遍历待上传目录下的文件*/
		for(File subDir:subDirs)
		{
			if(conSet != null && conSet.contains(subDir.getName()))
				continue;
			
			File[] validFiles = subDir.listFiles(new FileFilter()
			{
				@Override
				public boolean accept(File f)
				{
					if(f.isFile() && f.getName().equals("README.TXT"))
						return true;
					else
						return false;
				}});
			
			StringBuffer content = new StringBuffer();
			for(File validFile:validFiles)
			{
				System.out.println("pre upload:" + validFile.getPath());
				
				String tmpStr = null;
				BufferedReader reader = new BufferedReader(new FileReader(validFile));
				while ((tmpStr = reader.readLine()) != null)
				{
					if(content.length() > 0) content.append(",");
					content.append(tmpStr.split("\\t")[1]);
				}
			}
			
			GraContent graContent = new GraContent();
			graContent.setName(subDir.getName().split("_")[1]);
			graContent.setContent(content.toString());
			graContent.setRemark(graContent.getContent().split(",")[0]);
			graContent.setCreateDate(new Date());
			int id = graContentService.add(graContent);
			readme.append(subDir.getName()).append("\t")
			      .append("http://localhost:8080/details.do?id=").append(id)
			      .append(System.getProperty("line.separator"));
		}
		
		/**5.写README.TXT文件*/
		FileOutputStream out = new FileOutputStream(readmeTxt, true);
		out.write(readme.toString().getBytes());
		out.close();
	}
	
	
	
	private static List<String> file2List(File file) throws Exception
	{
		List<String> list = null;
		
		if(file.exists() && file.isFile() && file.canRead())
		{
			String tmpStr = null;
			BufferedReader reader = new BufferedReader(new FileReader(file));
			while ((tmpStr = reader.readLine()) != null)
			{
				if(list == null)
					list = new ArrayList<String>();
				list.add(tmpStr);
			}
		}
		
		return list;
	}
	
	
	public static void main(String[] args) throws Exception
	{
//		uploadPic("D:/xiaoniu1");
//		addWeibo("D:/xiaoniu1");
		uploadMil("D:/xiaoniu1");
		
//		OAuthV1 oAuth = new OAuthV1();
//		oAuth.setOauthConsumerKey("801115505");
//		oAuth.setOauthConsumerSecret("be1dd1410434a9f7d5a2586bab7a6829");
//		oAuth.setOauthToken("af51069722f04c15911cdf25b91bfe58");
//		oAuth.setOauthTokenSecret("81a98d6117ad686eb3aad86061707e4a");
//		TAPIExtend tpai = new TAPIExtend(oAuth.getOauthVersion());
////		String resp = tpai.addPic(oAuth, "json", "是否是否奶妈是南非赛飞不苏杭不", "127.0.0.1", "", "", "http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1307/30/c2/23923657_23923657_1375155634859_mthumb.jpg", "1");
//		String resp = tpai.uploadPic(oAuth, "json", null, "D:/xiaoniu/23854099_23854099_1374996659467_mthumb.jpg", 2);
		
	}
}
